﻿using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;

namespace mDaemon
{

    class HttpFileServer
    {
        static HttpFileServer instance;
        public static HttpFileServer getInstance()
        {
            if (instance == null) instance = new HttpFileServer();
            return instance;
        }

        private Thread _thread;
        private HttpListener _listener;
        public void start(int port, string path)
        {
            if (_thread != null) throw new Exception("duplicated thread for server");
            _thread = new Thread(() => _start(port, path));
            _thread.Start();
        }

        public void exit()
        {
            if(_listener != null) _listener.Close();
            if (_thread != null) _thread.Abort();
        }

        void _start(int port, string path)
        {      
            _listener = new HttpListener();
            _listener.Prefixes.Add("http://127.0.0.1"+":"+ port+"/");
            _listener.Prefixes.Add("http://localhost" + ":" + port + "/");
            _listener.Start();
            Console.WriteLine("Listening...");

            while (true)
            {
                HttpListenerContext context = _listener.GetContext();
                HttpListenerResponse response = context.Response;

                string page = path + "/" + context.Request.Url.LocalPath;
                var path1 = Path.GetFullPath(page);

                Console.WriteLine("Returning..."+ path1);

                try
                {
                    TextReader tr = new StreamReader(path1);
                    string msg = tr.ReadToEnd();

                    byte[] buffer = Encoding.UTF8.GetBytes(msg);

                    response.ContentLength64 = buffer.Length;
                    Stream st = response.OutputStream;
                    st.Write(buffer, 0, buffer.Length);
                }catch(Exception ex)
                {
                    Console.WriteLine(ex);
                }

                context.Response.Close();
            }

        }
    }

}